package org.hilo.boot.scaffold;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.jretty.log.LogFactory;
import org.jretty.log.Logger;
import org.jretty.util.Const;
import org.jretty.util.FileUtils.TextFileParse;
import org.jretty.util.IOUtils;
import org.jretty.util.NestedRuntimeException;
import org.jretty.util.StringUtils;

import org.hilo.boot.core.UT;

/**
 * 
 * @author zollty
 * @since 2020年5月27日
 */
class SgTools {
    
    private static final Logger LOG = LogFactory.getLogger(SgTools.class);
    
    /**
     * 打开目录
     */
    public static boolean open(String dir) {
        String osName = System.getProperty("os.name");
        if (osName != null) {
            try {
                if (osName.contains("Mac")) {
                    Runtime.getRuntime().exec("open " + dir);
                    return true;
                } else if (osName.contains("Windows")) {
                    Runtime.getRuntime().exec("cmd /c start " + dir);
                    return true;
                }
            } catch (Exception e) {
                // ignore...
            }
        }
        return false;
    }
    
    
    /**
     * 获取 目录以及子目录中的所有文件
     * @param inludeType 文件结尾类型（endsWith），比如 jpg, .jpg 都可以
     */
    public static List<File> loopFiles(File file, String[] inludeType) {
        ArrayList<File> result = new ArrayList<File>();
        if (file.isFile() && checkFileType(file, inludeType)) {
            result.add(file);
        }
        else if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null) {
                LOG.warn("cannot read dir " + file.getAbsolutePath());
                return result;
            }
            for (File filePath : files) {
                result.addAll(loopFiles(filePath, inludeType));
            }
        }
        return result;
    }
    
    private static boolean checkFileType(File file, String inludeType[]) {
        if (inludeType == null) {
            return true;
        }
        String name = file.getName();
        for (String type : inludeType) {
            if (name.endsWith(type)) {
                return true;
            }
        }
        return false;
    }
    
    
    /**
     * 按行解析文本文件
     */
    public static void parseTextFileAndWrite2Target(String fileFullPath, TextFileParse<String> parser, String targetPath) {
        InputStream in;
        try {
            in = new FileInputStream(fileFullPath);
        }
        catch (FileNotFoundException e) {
            throw new NestedRuntimeException(e);
        }
        
        BufferedWriter out = null;
        try {
            File file1 = new File(targetPath);
            File fileParent = file1.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file1.createNewFile();
            
            out = UT.File.getBufferedWriter(targetPath, false, Const.DEFAULT_CHARSET);
        }
        catch (IOException e) {
            IOUtils.closeIO(in);
            throw new NestedRuntimeException(e);
        }
        
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(in, Const.DEFAULT_CHARSET));
            String o;
            String lineStr;
            while ((lineStr = br.readLine()) != null) {
                if (StringUtils.isNotEmpty(lineStr)) {
                    // 读出文件中一行的数据
                    o = parser.parseOneLine(lineStr);
                    if (o != null) {
                        out.append(o).append("\r\n");
                    }
                } else {
                    out.append(lineStr).append("\r\n");
                }
            }
        }
        catch (Exception e) {
            throw new NestedRuntimeException(e);
        }
        finally {
            IOUtils.closeIO(out);
            IOUtils.closeIO(br);
        }
    }
    
    public static File createTempDir(String folderName) {
        File tmpdir = new File(System.getProperty("java.io.tmpdir"));
        tmpdir = new File(tmpdir, folderName);
        if (!tmpdir.exists()) {
            tmpdir.mkdir();
        }
        return tmpdir;
    }
    
    public static void replaceFile(String fullFileName, String content) {
        BufferedWriter bw = null;
        try {
            UT.File.forceMkdirParent(new File(fullFileName));

            bw = UT.File.getBufferedWriter(fullFileName, false, Const.UTF_8);
            bw.write(content);
            bw.flush();

        } catch (IOException e) {
            throw new NestedRuntimeException(e);
        } finally {
            UT.IO.closeIO(bw);
        }
    }
    
    static String stripMiddleOfIndex(String str, String index1, String index2) {
        int idx1 = str.indexOf(index1);
        if (idx1 == -1) {
            return str;
        }
        String org = str;
        String before = org.substring(0, idx1);
        str = org.substring(idx1 + index1.length(), org.length());
        int idx2 = str.indexOf(index2);
        if (idx2 == -1) {
            return org;
        }
        return before + str.substring(idx2 + index2.length(), str.length());
    }
    
    static String replaceBetween(String str, String index1, String index2, String newStr) {
        int idx1 = str.indexOf(index1);
        if (idx1 == -1) {
            return str;
        }
        String org = str;
        String before = org.substring(0, idx1);
        str = org.substring(idx1 + index1.length(), org.length());
        int idx2 = str.indexOf(index2);
        if (idx2 == -1) {
            return org;
        }
        return before + index1 + newStr + index2
                + str.substring(idx2 + index2.length(), str.length());
    }

}
